<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              :disabled="detailsDisabled"
              placeholder="请输入角色姓名"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium">搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建角色" size="medium" icon="el-icon-plus" perms="PT_ROLE_ADD" type="primary"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh">刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        class="elTable">
        <el-table-column type="index" label="序号" width="80" align="center"/>
        <el-table-column prop="roleName" label="角色名称" align="center"/>
        <el-table-column prop="roleDes" label="角色描述" show-overflow-tooltip align="center"/>
        <el-table-column prop="createByName" label="创建人" align="center"/>
        <el-table-column prop="createTime" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column prop="updateByName" label="更新人" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="450" align="center">
          <template #default="{ row }">
            <!--            <el-button type="primary" size="mini" @click="handlerEditEquipment(row)">分配项目权限-->
            <!--            </el-button>-->
            <perButton label="分配菜单权限" type="primary" size="mini" :disabled="row.roleCode == 'RO001'"
                       perms="PT_ROLE_BUTTON" @click="handlerMenuPermission(row)"></perButton>
            <perButton label="分配操作权限" type="primary" size="mini" :disabled="row.roleCode == 'RO001'"
                       perms="PT_ROLE_BUTTON" @click="handlerOperationPermission(row)"></perButton>
            <perButton label="编辑" type="warning" size="mini" :disabled="row.roleCode == 'RO001'" perms="PT_ROLE_EDIT"
                       @click="handlerEdit(row)"></perButton>
            <perButton label="删除" type="danger" size="mini" :disabled="row.roleCode == 'RO001'" perms="PT_ROLE_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 弹框 -->
    <yc-dialog ref="ycDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="loginFormRef"
            :model="newAccountModel"
            :rules="rules"
            label-width="90px"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input
                v-model="newAccountModel.roleName"
                :disabled="detailsDisabled"
              />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input
                v-model="newAccountModel.roleDes"
                :disabled="detailsDisabled"
              />
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 菜单权限 -->
    <yc-dialog ref="menuDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <!-- @select="select" @select-all="selectAll" @selection-change="handleSelectionChange" -->
        <el-table ref="multipleTable" border :data="tableData2" tooltip-effect="dark" row-key="id"
                  @select="select" @select-all="selectAll" @selection-change="handleSelectionChange"
                  :select-on-indeterminate="true"
                  :tree-props="{
                      label: 'menuName',
                      children: 'children',
                      hasChildren: 'hasChildren'}">
          <el-table-column type="selection" align="center" width="100"></el-table-column>
          <el-table-column prop="menuName" label="菜单名称">
          </el-table-column>
        </el-table>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="menuDialogSave()">确定</el-button>
        <el-button @click="$refs.menuDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 操作权限 -->
    <yc-dialog ref="operationPermissionDialog" centerTitle="操作权限" dialogTitle="操作权限">
      <template #content>
        <el-tabs tab-position="left">
          <el-tab-pane
            v-for="(item, index) in roleButtonList"
            :key="item.menuCode"
            :label="item.menuName">
            <el-checkbox
              v-for="itemB in item.roleButton"
              :key="itemB.buttonCode"
              v-model="itemB.isCheck"
              :label="itemB.isCheck"
            >{{itemB.buttonName}}
            </el-checkbox>
          </el-tab-pane>
        </el-tabs>
      </template>
      <template #footer>
        <el-button type="primary" :loading="projectPermission" @click="saveOperationPermission">保存</el-button>
        <el-button @click="$refs.operationPermissionDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message v-if="isGlobalMessageShow" @receive="receive" :message="message"/>
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryRolePage,
    updateRole,
    insertRole,
    deleteRole,
    updateRoleToMenu,
    queryRoleToMenu,
    queryRoleToButton,
  } from "@/api/userControl/role"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        isGlobalMessageShow: false,
        message: "",

        loading: false,
        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 10,

        searchModel: {
          userName: "",
          status: "" //正常/停用状态（全部）
        },

        newAccountModel: {
          roleName: "",
          roleDes: "",
          roleCode: ""
        },
        rules: {
          roleName: [
            {required: true, message: "请输入角色名称", trigger: "blur"}
          ]
        },

        centerTitle: "",
        dialogTitle: "",

        tableData2: [],
        multipleSelection: [],
        editorId: "",
        tableItemObj: {},
        roleCode: "",
        roleButtonList: [],
        detailsDisabled: false,
        addOrUpdateLoading: false,
        projectPermission: false
      }
    },
    created() {
      this.getAccountData()
    },
    methods: {
      // 搜索按钮
      async searchClick() {
        this.getAccountData(1, 10, this.searchModel)
      },
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const {userName, status} = tableInfo
          const {object} = await queryRolePage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            roleName: userName
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const {object} = await queryRolePage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },

      /**
       * 删除按钮
       */
      async handlerDelete({id}) {
        this.$confirm("确定删除此角色吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {message, status} = await deleteRole({id})
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },

      /**
       * 新建
       * */
      async handlerAccount() {
        this.centerTitle = "添加角色"
        this.dialogTitle = "添加角色"
        if (this.$refs.multipleTable) {
          this.$refs.multipleTable.clearSelection()
        }
        this.editorId = ""
        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs.loginFormRef) {
          this.$refs.loginFormRef.clearValidate()
          this.$refs.loginFormRef.resetFields()
        }
        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
      },
      /**
       * 修改按钮
       */
      async handlerEdit(row) {
        this.centerTitle = "编辑角色"
        this.dialogTitle = "编辑角色"
        this.editorId = row.id
        if (this.$refs.multipleTable) {
          this.$refs.multipleTable.clearSelection()
        }


        this.addOrUpdateLoading = false
        this.detailsDisabled = false
        this.$refs.ycDialog.dialogVisible = true
        if (this.$refs.loginFormRef) {
          this.$refs.loginFormRef.clearValidate()
          this.$refs.loginFormRef.resetFields()
        }
        this.newAccountModel.roleName = row.roleName
        this.newAccountModel.roleCode = row.roleCode
        this.newAccountModel.roleDes = row.roleDes
      },
      dialogSave() {
        this.$refs.loginFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true

            if (this.detailsDisabled) {
              // 详情的确定
              this.$refs.ycDialog.dialogVisible = false
            } else if (this.editorId) {
              const {roleCode, roleName, roleDes} = this.newAccountModel
              const {message, status} = await updateRole({
                roleCode,
                roleName,
                roleDes,
                id: this.editorId
              })

              if (status == 200) {
                this.$message.success(message)
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
              }
            } else {
              const {message, status} = await insertRole({
                ...this.newAccountModel
              })

              if (status == 200) {
                this.$message.success(message)
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      // 分配菜单权限
      async handlerMenuPermission(row) {
        this.centerTitle = "菜单权限"
        this.dialogTitle = "分配菜单权限"

        await this.queryRoleToMenu(row)

        this.tableItemObj = JSON.parse(JSON.stringify(row))

        this.addOrUpdateLoading = false
        this.$refs.menuDialog.dialogVisible = true
      },

      async queryRoleToMenu(val) {
        let params = {}
        if (val) {
          params = {
            roleCode: val.roleCode
          }
        }
        const data = await queryRoleToMenu(params)
        this.tableData2 = data.object
        this.checkShow(data.object, true)
      },

      checkShow(data, isShow) {
        data.forEach((e) => {
          if (e.mapString1 == "1") {
            setTimeout(() => {
              this.$refs.multipleTable.toggleRowSelection(e, isShow)
              if (e.children.length) {
                e.children.forEach((v) => {
                  if (v.mapString1 == "1") {
                    this.$refs.multipleTable.toggleRowSelection(v, isShow)
                  }
                })
              }
            })
          }
        })
      },

      handleSelectionChange(val) {
        this.multipleSelection = val
      },

      setChildren(children, type) {
        // 编辑多个子层级
        children.map((j) => {
          this.toggleSelection(j, type)
          if (j.children.length > 0) {
            this.setChildren(j.children, type)
          }
        })
      },
      toggleSelection(row, select) {
        if (row) {
          this.$nextTick(() => {
            this.$refs.multipleTable &&
            this.$refs.multipleTable.toggleRowSelection(row, select)
          })
        }
      },
      // 选中父节点时，子节点一起选中取消
      select(selection, row) {
        if (row.children.length) {
          const hasSelect = selection.some((el) => {
            return row.id === el.id
          })

          if (hasSelect) {
            if (row.children.length > 0) {
              // 解决子组件没有被勾选到
              this.setChildren(row.children, true)
            }
          } else {
            if (row.children.length > 0) {
              this.setChildren(row.children, false)
            }
          }
        }


        this.tableData2.forEach((item) => {
          if (item.id === row.fatherId) {
            this.$nextTick(() => {
              this.$refs.multipleTable &&
              this.$refs.multipleTable.toggleRowSelection(item, true)
            })
          }
        })
      },

      // 选择全部
      selectAll(selection) {
        // tabledata第一层只要有在selection里面就是全选
        const isSelect = selection.some((el) => {
          const tableDataIds = this.tableData2.map((j) => j.id)
          return tableDataIds.includes(el.id)
        })
        // tableDate第一层只要有不在selection里面就是全不选
        const isCancel = !this.tableData2.every((el) => {
          const selectIds = selection.map((j) => j.id)
          return selectIds.includes(el.id)
        })
        if (isSelect) {
          selection.map((el) => {
            if (el.children) {
              // 解决子组件没有被勾选到
              this.setChildren(el.children, true)
            }
          })
        }
        if (isCancel) {
          this.tableData2.map((el) => {
            if (el.children) {
              // 解决子组件没有被勾选到
              this.setChildren(el.children, false)
            }
          })
        }
      },

      async menuDialogSave() {
        this.addOrUpdateLoading = true
        const arr = []
        this.$refs.multipleTable.selection.forEach((e) => {
          arr.push(e.id)
        })
        const str = arr.join("&")
        const {roleCode} = this.tableItemObj
        const {
          message,
          status
        } = await updateRoleToMenu({
          roleCode, mapString1: str
        })

        if (status == "200") {
          this.$refs.menuDialog.dialogVisible = false
          this.getAccountData()
          this.$message.success(message)
        }
      },

      // 分配操作权限
      handlerOperationPermission({roleCode}) {
        this.roleButtonList = []
        this.roleCode = roleCode
        queryRoleToButton({roleCode}).then(res => {
          this.roleButtonList = res.object
        })
        this.$refs.operationPermissionDialog.dialogVisible = true
      },
      saveOperationPermission() {
        let arr = []
        for (let i = 0; i < this.roleButtonList.length; i++) {
          for (let j = 0; j < this.roleButtonList[i].roleButton.length; j++) {
            if (this.roleButtonList[i].roleButton[j].isCheck == true) {
              arr.push(this.roleButtonList[i].roleButton[j].buttonCode)
            }
          }
        }
        insertRoleBindMenButton({
          roleCode: this.roleCode,
          buttonString: arr.toString()
        }).then(res => {
          if (res.status == "200") {
            this.$message.success(res.message)
            this.$refs.operationPermissionDialog.dialogVisible = false
          }
        })
      },

      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {}
        this.getAccountData()
      },
      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },

    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      /*margin: 10px 20px;*/
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }



  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
